<?php
/**
 * 
 * HTTP Header Class
 * @author G. Peleskei
 *
 */
class Header {
	/**
	 * 
	 * Origin of Request
	 * @var String
	 */
	public $origin = null;
	/**
	 * 
	 * Requested URL
	 * @var String
	 */
	public $request = null;
	/**
	 * 
	 * Host
	 * @var String
	 */
	public $host = null;
	/**
	 * 
	 * Unique handshake key
	 * @var String
	 */
	public $key = null;
	/**
	 * 
	 * WebSocket Version
	 * @var String
	 */
	public $version = null;
	/**
	 * 
	 * Message Body
	 * @var String
	 */
	public $data = null;
	/**
	 * Information on Get Vars
	 * @var Array ("name" => NameOfVar, "value" => ValueOfVar);
	 */
	public $getter = array();
	
	/**
	 * 
	 * Constructor: Saves some Information from Handshake-Header
	 * @param String $header
	 */
	public function __construct($header) {
		if(preg_match("/GET (.*) HTTP/", $header, $match)) { 
			$this->request = $match[1]; 
		}
	  if(preg_match("/Host: (.*)\r\n/", $header, $match)) { 
	  	$this->host = $match[1]; 
	  }
	  if(preg_match("/Origin: (.*)\r\n/", $header, $match)) { 
	  	$this->origin = $match[1]; 
	  }
	  if(preg_match("/Sec-WebSocket-Key: (.*)\r\n/", $header, $match)) { 
	  	$this->key = $match[1]; 
	  }
		if(preg_match("/Sec-WebSocket-Version: (.*)\r\n/", $header, $match)) { 
			$this->version = $match[1];  
		}
	  if(preg_match("/\r\n(.*?)\$/", $header, $match)) {
	  	$this->data = $match[1]; 
	  }
	  $this->getter = $this->readGetInformation($this->request);
	}
	
	/**
	 * 
	 * Get GET Informations
	 * @param String $get
	 */
	protected function readGetInformation($get) {
	if (preg_match_all("/([^=\?&]+)=([^=\?&]*)/", $get, $match)) {
			$list = array();
			for ($i=0; $i<count($match[1]); $i++) {
				$list[] = array("name" => $match[1][$i], "value" => $match[2][$i]);
			}
			return $list;
		} else {
			return array();
		}
	}
	
	/**
	 * 
	 * Get Value of $name GET
	 * @param String $name
	 */
	protected final function getValue($name) {
		foreach($this->getter as $get) {
			if ($get["name"] == $name) return $get["value"];
		}
		return null;
	}
}
?>